var lang = {};
var TotalTime = 5;
var tTime = "";
var src = baselocation+"/login/check_verify/";
Storage.poolClear();
$.ajaxSetup({
    type: 'POST',
    dataType: 'json',
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.status == 403) {
            var a = $.parseJSON(XMLHttpRequest.responseText);
            error(get_translation(a['23']));
        } else if (XMLHttpRequest.status == 401) {
            $.cookie('ninja_clearance', null, {
                path: '/',
                expires: -5
            });
            $('#auth').show();
            $('#login').hide();
            Captcha.load();
        } else {
            error(get_translation('SYSTEM_ERROR'));
        }
    }
});
$(document).ready(function() {
    lang = detectLang();
    $('body').append('<div  id="ajaxBusy" style="display:none;position:absolute;left:0;top:0;width:100%;height:100%;"><div style="position: absolute; left:0; top:0; margin:0; width: 100%; height:100%; background: #404040; opacity: 0.5; z-index: 99999;"></div><div style="position: absolute; top: 50%; left: 50%; margin-left: -64px; z-index: 100000;"><img src="'+baselocation+'/style/member/img/ajax-loader.gif"></div></div>');
});
$(document).ajaxStart(function() {
    $('#ajaxBusy').show();
}).ajaxStop(function() {
    $('#ajaxBusy').hide();
});
var url = 11111;
var good_pass = 0; (function($) {
    $.fn.resultStyle = "";
    $.fn.passStrength = function(options) {
        var defaults = {
            shortPass: "shortPass",
            badPass: "badPass",
            goodPass: "goodPass",
            strongPass: "strongPass",
            baseStyle: "testresult",
            userid: "",
            messageloc: 1
        };
        var opts = $.extend(defaults, options);
        return this.each(function() {
            var obj = $(this);
            $(obj).unbind().keyup(function() {
                var results = $.fn.teststrength($(this).val(), $(opts.userid).val(), opts);
                if (opts.messageloc === 1) {
                    $(this).next("." + opts.baseStyle).remove();
                    $(this).after("<span class=\"" + opts.baseStyle + "\"><span></span></span>");
                    $(this).next("." + opts.baseStyle).addClass($(this).resultStyle).find("span").text(results);
                } else {
                    $(this).prev("." + opts.baseStyle).remove();
                    $(this).before("<span class=\"" + opts.baseStyle + "\"><span></span></span>");
                    $(this).prev("." + opts.baseStyle).addClass($(this).resultStyle).find("span").text(results);
                }
            });
            $.fn.teststrength = function(password, username, option) {
                var score = 0;
                good_pass = 0;
                if (password.length < 4) {
                    this.resultStyle = option.shortPass;
                    return $(this).shortPass;
                }
                if (password.toLowerCase() == username.toLowerCase()) {
                    this.resultStyle = option.badPass;
                    return $(this).samePassword;
                }
                score += password.length * 4;
                score += ($.fn.checkRepetition(1, password).length - password.length) * 1;
                score += ($.fn.checkRepetition(2, password).length - password.length) * 1;
                score += ($.fn.checkRepetition(3, password).length - password.length) * 1;
                score += ($.fn.checkRepetition(4, password).length - password.length) * 1;
                if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {
                    score += 5;
                }
                if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) {
                    score += 5;
                }
                if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
                    score += 10;
                }
                if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {
                    score += 15;
                }
                if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)) {
                    score += 15;
                }
                if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)) {
                    score += 15;
                }
                if (password.match(/^\w+$/) || password.match(/^\d+$/)) {
                    score -= 10;
                }
                if (score < 0) {
                    score = 0;
                }
                if (score > 100) {
                    score = 100;
                }
                if (score < 34) {
                    this.resultStyle = option.badPass;
                    good_pass = 0;
                    return $(this).badPass;
                }
                if (score < 68) {
                    this.resultStyle = option.goodPass;
                    good_pass = 1;
                    return $(this).goodPass;
                }
                good_pass = 1;
                this.resultStyle = option.strongPass;
                return $(this).strongPass;
            };
        });
    };
})(jQuery);
$.fn.checkRepetition = function(pLen, str) {
    var res = "";
    for (var i = 0; i < str.length; i++) {
        var repeated = true;
        for (var j = 0; j < pLen && (j + i + pLen) < str.length; j++) {
            repeated = repeated && (str.charAt(j + i) == str.charAt(j + i + pLen));
        }
        if (j < pLen) {
            repeated = false;
        }
        if (repeated) {
            i += pLen - 1;
            repeated = false;
        } else {
            res += str.charAt(i);
        }
    }
    return res;
}; 
(function($) {
    $.cookie = function(key, value, options) {
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({},
            options);
            if (value === null || value === undefined) {
                options.expires = -1;
            }
            if (typeof options.expires === 'number') {
                var days = options.expires,
                t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }
            value = String(value);
            return (document.cookie = [encodeURIComponent(key), '=', options.raw ? value: encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', options.path ? '; path=' + options.path: '', options.domain ? '; domain=' + options.domain: '', options.secure ? '; secure': ''].join(''));
        }
        options = value || {};
        var decode = options.raw ?
        function(s) {
            return s;
        }: decodeURIComponent;
        var pairs = document.cookie.split('; ');
        for (var i = 0,
        pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || '');
        }
        return null;
    };
})(jQuery);
function urldecode(str) {
    return decodeURIComponent((str + '').replace(/%(?![\da-f]{2})/gi,
    function() {
        return '%25';
    }).replace(/\+/g, '%20'));
}
function log(m) {
    if (window.console) {
        console.log(m);
    } else {
        alert(m);
    }
}
function get_translation(text) {
    translation = lang['vars'][text];
    return translation ? translation: text;
}
function handleState(data) {
    return data[8] == 0;
}
function isRecovery() {
    return new Rxp('recover').test(window.location.pathname);
}
function do_translate() {
    if (! (typeof(lang['vars']) == 'undefined')) {
        $.each($('.translate, title'),
        function(id, value) {
            if (!$(value).data('source')) {
                $(value).data('source', $(value).html());
            }
            $(value).html(get_translation($(value).data('source')));
            var attr = $(value).attr('title') ? $(value).attr('title') : $(value).data('title_source');
            if (attr) {
                if (!$(value).data('title_source')) {
                    $(value).data('title_source', attr);
                }
                $(value).attr('title', get_translation(attr));
            }
        });
        $.fn.shortPass = get_translation('TOO_SHORT');
        $.fn.badPass = get_translation('SIMPLE');
        $.fn.goodPass = get_translation('GOOD');
        $.fn.strongPass = get_translation('VERY_GOOD');
        $.fn.samePassword = get_translation('SAME_AS_USERNAME');
    }
}
$(function() {
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 9) {
        $("#container").html(get_translation('IE_NOT_SUPPORT')).css("padding", "20px");
        return;
    }
    do_translate();
    $(".corner").corner("round 8px").parent().css('padding', '4px').corner("round 10px").find(".content").corner("round 8px");
    $(".def_input").corner("round 5px");
    $(".def_button").corner("round 8px");
});
function error(m) {
    myalert(m);
}
function message(m) {
    alert(m);
}
function myalert(_m, _header, _callback) {
    var header = _header || get_translation('ALERT');
    var callback = _callback ||
    function() {};
    var div = $('<div id="myalert" style=" min-height:100px;min-width:150px;"><h3>' + header + '</h3>' + '<div>' + _m + '</div>' + '<p style="text-align:center; margin-top: 20px;"><button id="myalert_ok" class="button_orange" title="' + get_translation('OK') + '">' + get_translation('OK') + '</button>' + '</p>' + '</div>');
    $('#myalert_ok', div).on('click',
    function() {
        $.modal.close();
        $('myalert').remove();
    });
    div.appendTo('body');
    div.modal({
        escClose: false,
        zIndex: 100000,
        onClose: function() {
            callback();
            $.modal.close();
            $('myalert').remove();
        }
    });
}
function malert(_m, _header, _callback) {
    var header = _header || get_translation('ALERT');
    var callback = _callback ||
    function() {};
    var div = $('<div class="alert"><label class="alert__bg" for="alerts"></label><div class="alert__inner"><label class="alert__close" for="alerts"></label><div id="alert_container"><h2>'+_header+'</h2><div style="margin: 20px 0 30px 0">'+_m+'</div></div></div></div>');
    $('.alert__close', div).on('click',
    function() {
        $.modal.close();
        $('.alert').remove();
    });
    div.appendTo('body');
    div.modal({
        escClose: false,
        zIndex: 100000,
        onClose: function() {
            callback();
            $.modal.close();
            $('.alert').remove();
        }
    });
}
function show_from_login() {
    $('#auth, #dialog_p').hide();
    $('#login').show();
    form_events();
}
function show_from_auth() {
    $('#auth').show();
    $('#login, #dialog_r, .dialog_r').show();
    $('#captcha-refresh').click();
}
function show_from_recovery() {
    $('#auth').hide();
    $('#login').hide();
    $('#dialog_r, .dialog_r').show();
}
function form_events() {
    if ($('#auth').is(":visible")) {
        if ($.cookie('ninja_clearance')) {
            if (isRecovery()) {
                show_from_recovery();
            } else {
                show_from_login();
            }
            return;
        }
        $('#do_auth_').focus().die().on('keypress', (function(e) {
            var key = e.which;
            if (key == 13) {
                $('#do_auth').click();
                return false;
            }
        }));
    } else if ($('#login').is(":visible")) {
        if ($.cookie('NINJA_LOGIN')) {
            $('#upass').focus();
        } else {
            $('#uname').focus();
        }
    }
}
function before_login() {
    var h = $.cookie('ninja_clearance');
    if (h) {
        $.ajax({
            url: '/login/validate',
            data: {
                h: h
            },
            dataType: 'JSON',
            success: function(data) {
                if (data.status == "success") {
                    if (isRecovery()) {
                        show_from_recovery();
                    } else {
                        show_from_login();
                    }
                } else {
                    Captcha.load();
                    $.cookie('ninja_clearance', null, {
                        path: '/',
                        expires: -5
                    });
                }
            }
        });
    } else {
     //   Captcha.load();
    }
    form_events();
}
function do_auth() {	
	 if (isRecovery()) {
         show_from_recovery();
      } else {
         show_from_login();
      }		
}
function do_login() {}
function do_login_step_2(ext) {
    var data = {
        'l': $('#uname').val(),
        'p': $('#upass').val(),
        'lng': lang.ident
    };
    data = $.extend(data, ext);
    $.ajax({
        url: '/5/' + url + '.npl',
        data: data,
        success: function(data) {
            if (handleState(data)) {
                $.cookie('NINJA_LOGIN', $('#uname').val(), {
                    path: '/',
                    expires: 360
                });
                if (data.need_show) {
                    $('#message_body').html(data.disclamer);
                    $('#message').modal({
                        escClose: false,
                        onClose: function() {
                            var add = $('#not_show').attr('checked') ? '?r=1': '';
                            window.location.href = data[43] + add;
                        }
                    });
                    $('#read_message').click(function() {
                        var add = $('#not_show').attr('checked') ? '?r=1': '';
                        window.location.href = data[43] + add;
                    });
                } else {
                    window.location.href = data[43];
                }
            } else {
                error(data[23]);
            }
        }
    });
    return false;
}
function do_login_step2() {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'l': $('#uname').val(),
            'p': $('#upass').val(),
            'c': $('#code').val(),
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                $.cookie('NINJA_LOGIN', $('#uname').val(), {
                    path: '/',
                    expires: 360
                });
                if (data.need_show) {
                    $('#message_body').html(data.disclamer);
                    $('#message').modal({
                        escClose: false,
                        onClose: function() {
                            var add = $('#not_show').attr('checked') ? '?r=1': '';
                            window.location.href = data[43] + add;
                        }
                    });
                    $('#read_').click(function() {
                        var add = $('#not_show').attr('checked') ? '?r=1': '';
                        window.location.href = data[43] + add;
                    });
                } else {
                    window.location.href = data[43];
                }
            } else {
                error(data[23]);
            }
        }
    });
    return false;
}
function do_code() {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'act': 'get_code',
            'l': $('#uname').val(),
            'p': $('#upass').val(),
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                if (parseInt(data.voiced)) {
                    $('#do_reqvoice').show();
                }
                message(get_translation('SEND_CODE').replace(/%number/, data[23]));
            } else {
                error(data[23]);
            }
        }
    });
    return false;
}
function do_voice() {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'act': 'get_code',
            'type': 'voice',
            'l': $('#uname').val(),
            'p': $('#upass').val(),
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                message(get_translation('VOICE_CODE').replace(/%number/, data[23]));
            } else {
                error(data[23]);
            }
        }
    });
    return false;
}

function do_change() {
    if ($('#new_password').val().length < 6) {
    	malert(get_translation('PASSWORD_TOO_SHORT'));
        $('#new_password').focus();
    } else if ($('#new_password').val() != $('#new_password_repeat').val()) {
        malert(get_translation('PASSWORDS_NOT_MATCH'));
        $('#new_password').focus();
    } else if (!good_pass) {
    	malert(get_translation('PASSWORD_TOO_SIMPLY'));
        $('#new_password').focus();
    } else {
        $.ajax({
            url: baselocation+'/login/recover/reset',
            data: {
                'changing_email': $('#changing_email').val(),
                'changing_code': $('#changing_code').val(),
                'new_password': $('#new_password').val(),
                'lng': lang.ident,
                'token':$('#token').val()
            },
            success: function(data) {
                if (data['code']==4) {
                    $.modal.close();
                    if(data.t==0){
                    	malert('Max allowed number of attempts is used');
                    }else{
                    	 malert('Wrong recovery code. Left tries:'+data.t);
                    }
                }else if (data['code']==1){
                	alert(get_translation('Password_is_changed'));
                	location.href=baselocation+"/";
                }else{
                	malert('Please try once again, be careful with correct values');
                }
            }
        });
    }
    return false;
}
function autoLogin(uuid) {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'uuid': uuid
        },
        success: function(data) {
            if (handleState(data)) {
                var r = '';
                if (data.need_referrer) {
                    r = 'setref';
                }
                window.location.href = data[43] + (data.need_show ? '#show_disclamer': '');
            }
        }
    });
}
function checkCapcha(code, success) {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'act': 'check_capcha',
            'check_capcha': code,
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                success();
            } else {
                message(get_translation('INVALID_CAPCHA'))
            }
        }
    });
}
function doReqVoice(code, success) {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'act': 'get_voice',
            'l': $('#uname').val(),
            'p': $('#upass').val(),
            'check_capcha': code,
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                success();
            } else {
                error(data[23]);
            }
        }
    });
    return false;
}
function doReqCard(code, success) {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'act': 'get_card',
            'l': $('#uname').val(),
            'p': $('#upass').val(),
            'check_capcha': code,
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                var card_num = data[23].num;
                $('span.code_num', '#sms_table_container').html(card_num);
                success();
            } else {
                error(data[23]);
            }
        }
    });
    return false;
}
function getCardInfo(success) {
    $.ajax({
        url: '/5/' + url + '.npl',
        data: {
            'act': 'get_card_info',
            'l': $('#uname').val(),
            'p': $('#upass').val(),
            'lng': lang.ident
        },
        success: function(data) {
            if (handleState(data)) {
                var card_num = data[23].num;
                $('span.code_num', '#sms_table_container').html(card_num);
                success();
                $('.code_present', '#sms_table_container').show();
                $('.code_no_present', '#sms_table_container').hide();
            } else {
                if (parseInt(data[8], 10) == 2) {
                    $('.code_present', '#sms_table_container').hide();
                    $('.code_no_present', '#sms_table_container').show();
                    success();
                } else {
                    error(data[23]);
                }
            }
        }
    });
    return false;
}
$(function() {
    before_login();
    $("#new_password").passStrength({
        userid: "#changing_email"
    });
    var h = urldecode(window.location.href);
    var exp_hash = new RegExp("^https?://[^/]+/recover/([A-Za-z0-9_\\-\\.]+@[A-Za-z0-9_\\-\\.]+)#([A-Za-z0-9]*)$");
    var address = window.location.href;
    if (exp_hash.test(address)) {
        address = address.replace('#', '/');
        window.location = address;
    }
    var pattern = "^https?://[^/]+/recover/((([A-Za-z0-9_\\-\\.]+@[A-Za-z0-9_\\-\\.]+)#([A-Za-z0-9]*))|([0-9]*))?$";
    pattern = pattern.replace('#', '/');
    var exp = new RegExp(pattern);
    if (h.match(exp)) {
        var ar = exp.exec(h);
        if (ar[2]) {
            $('#changing_email').val(ar[3]);
            $('#changing_code').val(ar[4]);
        } else {
            $('#et').html(get_translation('PHONE_NUMBER'));
            if (ar[5]) {
                $('#changing_email').val(ar[5]);
            }
        }
        if (!$.cookie('ninja_clearance')) {
            show_from_auth();
        } else {
            $('#dialog_r, .dialog_r').show();
        }
    } else {
        var n = $.cookie('NINJA_LOGIN') || '';
        if (n) {
            $('#uname').val(n);
        }
    }
    exp = new RegExp("^https?://[^/]+/\\#uuid=([A-Za-z0-9_]+)$");
    if (h.match(exp)) {
        var ar = exp.exec(h);
        if (ar[1]) {
            autoLogin(ar[1]);
        }
    }
    $('.modal_close').die().live('click',
    function() {
        $.modal.close();
        return false;
    });
    $('#do').die().live('click',
    function() {
        do_login();
        return false;
    });
    $('#do_auth').die().live('click',
    function() {
        do_auth();
        return false;
    });
//    $('#captcha-refresh').die().on('click',
//    function() {
//        Captcha.load();
//        return false;
//    });
    $('#do_login').die().live('click',
    function() {
        do_login_step2();
        return false;
    });
    $('#do_reqsms').die().live('click',
    function() {
        do_code();
        return false;
    });
    $('#do_reqvoice').die().live('click',
    function() {
        do_voice();
        return false;
    });
    $('#code').keypress(function(e) {
        if (e.which == 13) {
            do_login_step2();
        }
    });
    $('#uname, #upass, #sms_code').keypress(function(e) {
        if (e.which == 13) {
            do_login();
        }
    });
    $('#recover').die().live('click',
    function() {
        $('#recovery_email').val($('#uname').val());
        $('#dialog').modal();
        return false;
    });
   
    $('#do_close').die().live('click',
    function() {
        $('#dialog').fadeOut();
        $.modal.close();
    });
    $('#do_close_change').die().live('click',
    function() {
        window.location.pathname = baselocation+"/";
		$('#dialog_r, .dialog_r').fadeOut();
        $.modal.close();
    });
   
    $('#do_change').die().live('click',
    function() {
      //  window.location.pathname = '/';
		do_change();
        return false;
    });
    $('#do_auth_type_back').click(function() {
        $('#add_auth').hide();
        $('#container').show();
        return false;
    });
    $('#do_auth_type').click(function() {
        var type = $('input[name="auth_type"]:checked', '#select_container').val();
        if (!type) {
            message(get_translation('SELECT_TYPE'));
        } else {
            if (type == 'ga') {
                $('.wizard', '#add_auth').hide();
                $('#ga_container').show();
            } else if (type == 'sms_table') {
                getCardInfo(function() {
                    $('.wizard', '#add_auth').hide();
                    $('#sms_table_container').show();
                });
            } else if (type == 'voice') {
                $('.wizard', '#add_auth').hide();
                $('#voice_container').show();
                $('img.capcha', '#voice_container').attr('src', '/c?' + (100000 * Math.random() + 10000));
            }
        }
        return false;
    });
    $('#do_request_sms_table').click(function() {
        $('.wizard', '#add_auth').hide();
        $('#request_sms_container').show();
        $('img.capcha', '#request_sms_container').attr('src', '/c?' + (100000 * Math.random() + 10000));
        return false;
    });
    $('#do_auth_type_voice_1_back, #do_auth_type_ga_back, #do_auth_type_sms_table_back').click(function() {
        $('.wizard', '#add_auth').hide();
        $('#select_container').show();
        return false;
    });
    $('#do_request_sms_table_2_back').click(function() {
        $('.wizard', '#add_auth').hide();
        $('#sms_table_container').show();
        return false;
    });
    $('#do_login_voice_1').click(function() {
        checkCapcha($('#voice_capcha').val(),
        function() {
            setTimeout(function() {
                doReqVoice($('#voice_capcha').val(),
                function() {
                    $('.wizard', '#add_auth').hide();
                    $('#voice_last_container').show();
                });
            },
            2000);
        });
        return false;
    });
    $('#do_request_sms_table_2').click(function() {
        doReqCard($('input[name="capcha"]', '#request_sms_container').val(),
        function() {
            $('.wizard', '#add_auth').hide();
            $('#sms_table_container').show();
            $('.code_present', '#sms_table_container').show();
            $('.code_no_present', '#sms_table_container').hide();
        });
        return false;
    });
    $('#do_login_sms_table').click(function() {
        var code = $('input[name="code"]', '#sms_table_container').val();
        if (!code) {
            return false;
        }
        do_login_step_2({
            'c': code,
            'ctype': 'sms'
        });
        return false;
    });
    $('#do_login_ga').click(function() {
        var code = $('input[name="code"]', '#ga_container').val();
        if (!code) {
            return false;
        }
        do_login_step_2({
            'c': code,
            'ctype': 'ga'
        });
        return false;
    });
    $('#do_login_voice_2').click(function() {
        var code = $('input[name="code"]', '#voice_last_container').val();
        if (!code) {
            return false;
        }
        do_login_step_2({
            'c': code,
            'ctype': 'voice'
        });
        return false;
    });
    $('a.recapcha').click(function() {
        $(this).parent().find('img.capcha').attr('src', '/c?' + (100000 * Math.random() + 10000));
    });
});
function setFromDomain() {

}
$('#recovery_email').keypress(function(e) {
    if (e.which == 13) {
        do_recover();
    }
});
$('#do_recover1').die().live('click',
	    function() {
	        do_recover();
	      //  return false;
	    });
function do_recover(){  
	 var m = $('#recovery_email').val();
	$.ajax({
		url:baselocation+"/login/getRecovery/",
		type: 'POST',
		data:{email:m},
		success:function(result){  
			if(result.code==1){				
				alert(get_translation('Email_is_sent'));
				location.href=baselocation+"/login/recover/"+m+"/";
			}else if(result.code==2){
				alert("User not found");
			}else if(result.code==200){
				alert("You should wait for recovery letter");
			}else{
				alert(get_translation('Email erro'));
			}
		}
	})       
}  
$(function() {
	$('#cap_ch').focus().die().on('keypress', (function(e) {
        var key = e.which;
        if (key == 13) {
            $('#do_auth_').click();
            return false;
        }
    }));
	$('#captcha-refresh').click(function() {
		$('#ajaxBusy').show();
		setTimeout(function(){
			var imgSrc = $("#codeImg");
			imgSrc.attr("src", chgUrl(src));
			$('#ajaxBusy').hide();
		},500);
		
	});
	$('#do_auth_').click(function() {
		$.ajax({
			url : baselocation + '/login/validateCap/',
			type : 'POST',
			data : {
				cap_ch : $('#cap_ch').val()
			},
			success : function(result) {
				if (result.code == 0) {
					malert(get_translation('INVALID_CAPCHA'),get_translation('ALERT'), false);
				}
				if (result.code == 1) {
					$("#auth").hide();
					$("#login").show();
					$('#token').val(result.token);
				}
			}
		})
	})
	$('#myalert_ok').click(function() {
		$("#myalert").css('display', 'none');
	})
	$('#dologin').click(function() {
		$('#ajaxBusy').show();
		$.cookie('NINJA_LOGIN',$('#uname').val(), { 
			path : '/',
			expires : 365
		});
	var langs =$.cookie('lang');
	if(langs=='id'){
		langs = 'iid_IID';
	}else if(langs=='cn'){
		langs = 'zh_CN';
	}else if(langs=='ru'){
		langs = 'ru_RU';
	}else{
		langs = 'en_US';
	}
	$.ajax({
		url : baselocation + "/login/",
		type : 'POST',
		data : {
			uname : $('#uname').val(),
			upass : $('#upass').val(),
			cap_ch : $('#cap_ch').val(),
			token : $('#token').val(),
			langs : langs
		},
		success : function(result) {
			$('#ajaxBusy').hide();
			if(result.newscode==0){
				location.href = baselocation+"/"+result.urlCode+"/news.html";
				return;
			}
			if (result.code == 0) {
				malert(get_translation('PASSWORDS_NOT_MATCH'),get_translation('ALERT'), false);
			}else if (result.code == 1) {
				location.href = baselocation+"/"+result.urlCode+"/desktop.html";
			}else if (result.code == 2) {
				location.href = baselocation+"/"+result.urlCode+"/tickets.html";
			}else if(result.code == 400) {
				show_from_auth_();
			}else{
				error(get_translation('SYSTEM_ERROR'));
			}
		}
	})
})
	open_index();
});
function open_index() {
	var n = $.cookie('NINJA_LOGIN');
	$("#login,#auth").hide();
	if(n!=null){
		show_from_auth_();
	}else{
		var imgSrc = $("#codeImg");
		imgSrc.attr("src", chgUrl(src));
		if (TotalTime > 0) {
			TotalTime--;
			$("#ts_msg").html(TotalTime);
			open_index();
		} else {
			clearTimeout(tTime);
			$("#beftor_login").hide();
			$("#auth").show();
			$.cookie('NINJA_LOGIN','', { 
				path : '/',
				expires : 365
			});
		}
	}
}

function chgUrl(url) {
	var timestamp = (new Date()).valueOf();
	url = url + "?v=" + timestamp;
	return url;
}
function show_from_auth_(){
	$('#ajaxBusy').show();
	$("#beftor_login").hide();
	$("#login").hide();
	$("#auth").show();
	var imgSrc = $("#codeImg");
	imgSrc.attr("src", chgUrl(src));
	$('#ajaxBusy').hide();
}
